package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

import java.util.function.Function;
import java.util.stream.Collectors;

/*
 * 菜品管理controller
 * */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("dishDto{}", dishDto);
        dishService.saveWithFlavor(dishDto);
        return R.success("新增成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        wrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, wrapper);
        Page<DishDto> dishDtoPage = new Page<>();
//        两个参数：全属性copy
//        三个参数：第三个参数指定忽略哪个参数
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<Dish> orders = pageInfo.getRecords();
        List<DishDto> dishDtoList = orders.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dishDtoList);
        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> getByIdWithFlavor(@PathVariable Long id) {
        Dish dish = dishService.getById(id);
        Long categoryId = dish.getCategoryId();
        Category category = categoryService.getById(categoryId);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        DishDto dishDto = new DishDto();
        dishDto.setCategoryName(category.getName());
        dishDto.setFlavors(list);
        BeanUtils.copyProperties(dish, dishDto);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("dishDto{}", dishDto);
/*        dishService.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(wrapper);
        List<DishFlavor> flavors = dishDto.getFlavors();
        List<DishFlavor> flavorList = flavors.stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
//            dishFlavorService.save(dishFlavor);
            return dishFlavor;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavorList);*/
        dishService.update(dishDto);
        return R.success("修改成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateById(@PathVariable int status, long[] ids) {
        log.info("状态status：{}", status);
        log.info("起售状态ids：{}", ids);
        List<Dish> list = new ArrayList<>();
        for (long id : ids) {
            Dish dish = new Dish();
            dish.setStatus(status);
            dish.setId(id);
            list.add(dish);
        }
        dishService.saveOrUpdateBatch(list);
        return R.success("状态修改成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("删除状态ids：{}", ids);
        dishService.deleteDishWithFlavor(ids);
        return R.success("删除成功");
    }


    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        log.info("categoryId=>{}", dish.getCategoryId());
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getStatus, 1);
        wrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        List<Dish> list = dishService.list(wrapper);
        List<DishDto> dishDtoList = list.stream().map(new Function<Dish, DishDto>() {
            @Override
            public DishDto apply(Dish dish) {
                DishDto dishDto = new DishDto();
                BeanUtils.copyProperties(dish, dishDto);
                Long categoryId = dish.getCategoryId();
                Category categoryName = categoryService.getById(categoryId);
                dishDto.setCategoryName(categoryName.getName());
                LambdaQueryWrapper<DishFlavor> dishFlavorWrapper = new LambdaQueryWrapper<>();
                dishFlavorWrapper.eq(DishFlavor::getDishId, dish.getId());
                List<DishFlavor> dishFlavors = dishFlavorService.list(dishFlavorWrapper);
                dishDto.setFlavors(dishFlavors);
                return dishDto;
            }
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
}
